package com.linkage.jz.bankruptcy.net;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.MainActivity;
import com.linkage.jz.bankruptcy.bean.TokenInfo;
import com.linkage.jz.bankruptcy.utils.HttpEventListener;
import com.linkage.jz.bankruptcy.utils.LogUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.utils.SignUtil;
import com.linkage.jz.bankruptcy.widget.LoginNoticeDialog;
import com.linkage.jz.bankruptcy.widget.PublicLoginNoticeDialog;
import com.linkage.seapeak.activity.register.RegisterActivity;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.BufferedSource;
import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class Network {
    private final static String TAG = "Network";

    private static AFAPIService apis;
    private static Converter.Factory mAfApiConverterFactory = GsonConverterFactory.create();
    private static CallAdapter.Factory rxJavaCallAdapterFactory = RxJavaCallAdapterFactory.create();
    private static ReLoginService mReLoginService;

    private static PublicLoginNoticeDialog publicLoginNoticeDialog;

    public static AFAPIService getAPIService() {
        if (apis == null) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            // OkHttp3.0的使用方式
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(3*60000l, TimeUnit.SECONDS)
                    .readTimeout(3*60000l, TimeUnit.SECONDS)
                    .eventListenerFactory(HttpEventListener.FACTORY)
                    .retryOnConnectionFailure(true)
                    .addInterceptor(new Interceptor() {
                        @Override
                        public Response intercept(Chain chain) throws IOException {
                            Request original = chain.request();
                            Request.Builder requestBuilder = original.newBuilder();


                            Random random = new Random();
                            String nonce = random.nextLong() + "";
                            String timestamp = System.currentTimeMillis() + "";

                            if (original.body() instanceof FormBody) {
                                FormBody.Builder newFormBody = new FormBody.Builder();

                                newFormBody.add("appid", Consts.APPID);
                                newFormBody.add("nonce", nonce);
                                newFormBody.add("timestamp", timestamp);
                                newFormBody.add("token", BankruptcyApp.tokeninfo.getToken());

                                FormBody oldFormBody = (FormBody) original.body();
                                for (int i = 0; i < oldFormBody.size(); i++) {
                                    newFormBody.addEncoded(oldFormBody.encodedName(i), oldFormBody.encodedValue(i));
                                }

                                requestBuilder.method(original.method(), newFormBody.build());
                            } else if (original.body() instanceof MultipartBody) {
                                MultipartBody.Builder newFormBody = new MultipartBody.Builder();
                                // 默认是multipart/mixed，大坑
                                newFormBody.setType(MediaType.parse("multipart/form-data"));
                                newFormBody.addFormDataPart("appid", Consts.APPID);
                                newFormBody.addFormDataPart("nonce", nonce);
                                newFormBody.addFormDataPart("timestamp", timestamp);
                                newFormBody.addFormDataPart("token", BankruptcyApp.tokeninfo.getToken());


                                MultipartBody oldFormBody = (MultipartBody) original.body();
                                for (int i = 0; i < oldFormBody.size(); i++) {
                                    newFormBody.addPart(oldFormBody.part(i));
                                }

                                requestBuilder.method(original.method(), newFormBody.build());
                            } else if (TextUtils.equals(original.method(), "POST")) {
                                FormBody.Builder newFormBody = new FormBody.Builder();
                                newFormBody.add("os", "android");
                                requestBuilder.method(original.method(), newFormBody.build());
                            }

                            Request request = requestBuilder.build();
                            Response response = chain.proceed(request);


                            Response.Builder builder = new Response.Builder();
                            String demo = "";
                            ResponseBody responseBody;
                            builder.headers(response.headers());
                            builder.code(response.code());
                            builder.request(request);
                            builder.protocol(response.protocol());
                            builder.message(response.message());


//                            if (original.url().url().getPath().endsWith("v1/open/api/manager/generate/result")) {
//                                LogUtil.w(TAG, "【DEMO---------->】表决生成结果");
//                                demo = "{\"code\":0,\"msg\":\"system.success\"," +
//                                        "\"data\":{\"voteId\":\"f9ed9250560a4c49bdbc8bd38fa880e1\",\"fileUrl\":\"http://xxx/group1/M00/00/12/rBHd5FzsqPyAZBXwAACwFWM5pGo927.pdf?token=f89fac1fb1e46b9933b302532ebbdd23&ts=1559013638\",\"resultId\":\"1929f3a8d81a40e08c41de620f828a69\"}}";
//                                responseBody = ResponseBody.create(MediaType.parse("application/json; charset=utf-8"), demo);
//                                builder.body(responseBody);
//                                return builder.build();
//                            }
//                            if (original.url().url().getPath().endsWith("/open/api/manager/vote/schedule")) {
//                                LogUtil.w(TAG, "【DEMO---------->】表决进度");
//                                String  demo1 = "{\"code\":0,\"msg\":\"system.success\",\"data\":{\"defaultAgreed\":false,\"dataList\":[{\"agreedVoterRate\":0.33,\"disAgreedNum\":1,\"noVoteNum\":0,\"notAttendAmount\":29991.00,\"groupId\":\"48752f4d9c41411a89f4d352d3b4b616\",\"notAtdMoneyRate\":0.77,\"agreedNum\":1,\"notAttendNum\":1,\"agreedMoneyRate\":0.08,\"noVoteAmount\":0.00,\"noVoteRate\":0.0,\"totalAmount\":38821.0000000000,\"groupName\":\"债务修改分组名称Q\",\"noVoteMoneyRate\":0.0,\"disAgreedMoneyRate\":0.13,\"disAgreedVoterRate\":0.33,\"totalMeetingMember\":3,\"agreedAmount\":3465.00,\"notAtdVoterRate\":0.33,\"disAgreedAmount\":5365.00},{\"agreedVoterRate\":0.5,\"disAgreedNum\":0,\"noVoteNum\":0,\"notAttendAmount\":5365.00,\"groupId\":\"da7da1a8be614c89b8bc542a14eb7d11\",\"notAtdMoneyRate\":0.19,\"agreedNum\":1,\"notAttendNum\":1,\"agreedMoneyRate\":0.8,\"noVoteAmount\":0.00,\"noVoteRate\":0.0,\"totalAmount\":27307.0000000000,\"groupName\":\"平台债务分组F\",\"noVoteMoneyRate\":0.0,\"disAgreedMoneyRate\":0.0,\"disAgreedVoterRate\":0.0,\"totalMeetingMember\":2,\"agreedAmount\":21942.00,\"notAtdVoterRate\":0.5,\"disAgreedAmount\":0.00}],\"status\":4}}";
//                                String  demo2 = "{\"code\":0,\"msg\":\"system.success\",\"data\":{\"agreedVoterRate\":0.4,\"defaultAgreed\":false,\"disAgreedNum\":1,\"notAttendAmount\":35356.0,\"noVoteNum\":0,\"notAtdMoneyRate\":0.53,\"agreedNum\":2,\"notAttendNum\":2,\"agreedMoneyRate\":0.38,\"noVoteAmount\":0.0,\"noVoteRate\":0.0,\"totalAmount\":66128.0,\"noVoteMoneyRate\":0.0,\"disAgreedMoneyRate\":0.08,\"disAgreedVoterRate\":0.2,\"totalMeetingMember\":5,\"agreedAmount\":25407.0,\"notAtdVoterRate\":0.4,\"status\":4,\"disAgreedAmount\":5365.0}}";
//                                responseBody = ResponseBody.create(MediaType.parse("application/json; charset=utf-8"), demo2);
//                                builder.body(responseBody);
//                                return builder.build();
//                            }

//                            if (original.url().url().getPath().endsWith("open/api/manager/vote/participants")) {
//                                LogUtil.w(TAG, "【DEMO---------->】表决详细");
//                                 demo = "{\"code\":0,\"msg\":\"system.success\",\"data\":{\"amount\":29991.0," +
//                                         "\"pageData\":{\"pageNo\":1,\"totalPage\":2,\"pageSize\":5,\"minPage\":1," +
//                                         "\"localArrayList\":[1],\"list\":[{\"creditorName\":\"王庆华\"," +
//                                         "\"bankruptcyProjectId\":\"c316f2035b994ab696889fb084b9d235\"," +
//                                         "\"groupId\":\"48752f4d9c41411a89f4d352d3b4b616\"," +
//                                         "\"voteId\":\"d8b7336332024acbbeae12238695ba97\",\"confirmedMoney\":5017" +
//                                         ".0000000000,\"meetingNumber\":5,\"voteOpinion\":0," +
//                                         "\"id\":\"s3qgoep2ecg98oqacj957hm1b8\"," +
//                                         "\"sysUserId\":\"f9ed9250560a4c49bdbc8bd38fa880e1\",\"voteMoney\":29991" +
//                                         ".0000000000,\"meeting\":false,\"vote\":false,\"voteTime\":1554422400," +
//                                         "\"onlineStatus\":1,\"creditorId\":\"b92e9def011043438797de782efd18cc\"," +
//                                         "\"allowChange\":false},{\"creditorName\":\"刘德华\"," +
//                                         "\"bankruptcyProjectId\":\"c316f2035b994ab696889fb084b9d235\"," +
//                                         "\"groupId\":\"48752f4d9c41411a89f4d352d3b4b616\"," +
//                                         "\"voteId\":\"d8b7336332024acbbeae12238695ba97\",\"confirmedMoney\":5017" +
//                                         ".0000000000,\"meetingNumber\":5,\"voteOpinion\":0," +
//                                         "\"id\":\"s3qgoep2ecg98oqacj957hm1b8\"," +
//                                         "\"sysUserId\":\"f9ed9250560a4c49bdbc8bd38fa880e1\",\"voteMoney\":29991" +
//                                         ".0000000000,\"meeting\":false,\"vote\":false,\"voteTime\":1554452400," +
//                                         "\"onlineStatus\":2,\"creditorId\":\"b92e9def011043438797de782efd18cc\"," +
//                                         "\"allowChange\":true}],\"totalCount\":1,\"maxPage\":1}}}";
//                                 responseBody = ResponseBody.create(MediaType.parse("application/json; charset=utf-8"), demo);
//                                 builder.body(responseBody);
//                                 return builder.build();
//                            }


//                            if (original.url().url().getPath().endsWith("/api/manager/vote/result/statistics")) {
//                                LogUtil.w(TAG, "【DEMO---------->】详情结果数据统计");
//                                // demo-已完成
//                                 demo = "{\"code\":\"0\",\"data\":{\"creator\":true,\"executor\":false,\"taskDetail\":{\"id\":\"ec26d67883dc4698bd5bcbd9c47675c2\",\"bankruptcyProjectId\":\"9c208e41eab641d59b88372c986605e9\",\"taskName\":\"任务名称20190408\",\"taskContent\":\"任务内容20190408\",\"memberId\":\"c32c1f4fafe9424485d54ae14ac7cab9\",\"deadlineTime\":1552355250,\"status\":{\"value\":2,\"text\":\"已完成\"},\"finishTime\":1554707246,\"feedbackMessage\":\"测试通知消息\",\"executor\":{\"id\":\"c32c1f4fafe9424485d54ae14ac7cab9\",\"loginname\":\"18655452308\",\"username\":\"18655452308\",\"avatar\":\"\",\"company\":null,\"userOnline\":true,\"disabled\":false,\"email\":null,\"mobile\":\"18655452308\",\"loginAt\":1554775592,\"loginIp\":\"127.0.0.1\",\"loginCount\":3,\"loginSessionId\":\"311iiiv9f2j5po1eo1qbr09j0n\",\"customMenu\":null,\"loginTheme\":null,\"menuTheme\":null,\"loginSidebar\":false,\"loginBoxed\":false,\"loginScroll\":false,\"loginPjax\":true,\"appInfoIdAndroid\":\"6748524783374e008f1103ea819a0fda\",\"appInfoIdIos\":null,\"unitid\":\"4db0951b9c5c4bbfbf6cf104cc2511c0\",\"unit\":null,\"appInfoIos\":null,\"appInfoAndroid\":null,\"roles\":null,\"units\":null,\"menus\":null,\"firstMenus\":null,\"secondMenus\":null,\"customMenus\":null,\"qq\":null,\"wx\":null,\"opBy\":\"\",\"opAt\":1552445670,\"delFlag\":false},\"creator\":{\"id\":\"93bec345da1d4699b2782c44bf190faf\",\"loginname\":\"18655752308\",\"username\":\"王富贵\",\"avatar\":\"group1/M00/00/04/rBHd5Fya1PmACFKoAAA7GwNBo1Q524.jpg\",\"company\":\"江苏萌发科技有限公司\",\"userOnline\":true,\"disabled\":false,\"email\":\"1262333517@qq.com\",\"mobile\":\"18655752308\",\"loginAt\":1555291645,\"loginIp\":\"127.0.0.1\",\"loginCount\":42,\"loginSessionId\":\"rshheaodbogbpo222899cl973s\",\"customMenu\":null,\"loginTheme\":\"palette.2.css\",\"menuTheme\":null,\"loginSidebar\":false,\"loginBoxed\":false,\"loginScroll\":true,\"loginPjax\":false,\"appInfoIdAndroid\":\"6748524783374e008f1103ea819a0fda\",\"appInfoIdIos\":null,\"unitid\":\"4db0951b9c5c4bbfbf6cf104cc2511c0\",\"unit\":null,\"appInfoIos\":null,\"appInfoAndroid\":null,\"roles\":null,\"units\":null,\"menus\":null,\"firstMenus\":null,\"secondMenus\":null,\"customMenus\":null,\"qq\":null,\"wx\":null,\"opBy\":\"93bec345da1d4699b2782c44bf190faf\",\"opAt\":1551945057,\"delFlag\":false},\"taskAtta\":[{\"id\":\"1\",\"bankruptcyProjectId\":\"9c208e41eab641d59b88372c986605e9\",\"taskId\":\"ec26d67883dc4698bd5bcbd9c47675c2\",\"attachmentName\":\"任务附件1\",\"attachmentSuffix\":\"jpg\",\"attachmentPreviewAddress\":null,\"attachmentDownloadAddress\":null,\"attachmentWatermarkAddress\":\"http://60 .205.186.115:8001/group1/M00/00/04/rBHd5Fya1PmACFKoAAA7GwNBo1Q524-wmark.jpg?token=f7a812c06e98190008e30ab3d545743b&ts=1555296297\",\"attachmentThumbnailAddress\":null,\"attachmentSize\":123,\"canDelete\":false,\"opBy\":null,\"opAt\":null,\"delFlag\":false},{\"id\":\"2\",\"bankruptcyProjectId\":\"9c208e41eab641d59b88372c986605e9\",\"taskId\":\"ec26d67883dc4698bd5bcbd9c47675c2\",\"attachmentName\":\"任务附件2\",\"attachmentSuffix\":\"jpg\",\"attachmentPreviewAddress\":null,\"attachmentDownloadAddress\":null,\"attachmentWatermarkAddress\":\"http://60.205.186 .115:8001/group1/M00/00/04/rBHd5Fya1PmACFKoAAA7GwNBo1Q524-wmark.jpg?token=f7a812c06e98190008e30ab3d545743b&ts=1555296297\",\"attachmentThumbnailAddress\":null,\"attachmentSize\":123,\"canDelete\":false,\"opBy\":null,\"opAt\":null,\"delFlag\":false}],\"opBy\":\"93bec345da1d4699b2782c44bf190faf\",\"opAt\":1554706728,\"delFlag\":false}}}";
//                                // demo-未完成
//                                demo = "{\"code\":0,\"msg\":\"system.success\"," +
//                                        "\"data\":{\"groupsList\":[{\"defaultAgreed\":false,\"agreedVoterRate\":0.33,\"disAgreedNum\":1,\"noVoteNum\":0,\"notAttendAmount\":29991.00,\"groupId\":\"48752f4d9c41411a89f4d352d3b4b616\",\"notAtdMoneyRate\":0.77,\"agreedNum\":1,\"notAttendNum\":1,\"agreedMoneyRate\":0.08,\"noVoteAmount\":0.00,\"noVoteRate\":0.0,\"totalAmount\":38821.0000000000,\"groupName\":\"债务修改分组名称Q\",\"noVoteMoneyRate\":0.0,\"disAgreedMoneyRate\":0.13,\"disAgreedVoterRate\":0.33,\"totalMeetingMember\":3,\"agreedAmount\":3465.00,\"notAtdVoterRate\":0.33,\"disAgreedAmount\":5365.00},{\"defaultAgreed\":false,\"agreedVoterRate \":0.5,\"disAgreedNum\":0,\"noVoteNum\":0,\"notAttendAmount\":5365.00,\"groupId\":\"da7da1a8be614c89b8bc542a14eb7d11\",\"notAtdMoneyRate\":0.19,\"agreedNum\":1,\"notAttendNum\":1,\"agreedMoneyRate\":0.8,\"noVoteAmount\":0.00,\"noVoteRate\":0.0,\"totalAmount\":27307.0000000000,\"groupName\":\"平台债务分组F\",\"noVoteMoneyRate\":0.0,\"disAgreedMoneyRate\":0.0,\"disAgreedVoterRate\":0.0,\"totalMeetingMember\":2,\"agreedAmount\":21942.00,\"notAtdVoterRate\":0.5,\"disAgreedAmount\":0.00}]}}";
//                                responseBody = ResponseBody.create(MediaType.parse("application/json; charset=utf-8"), demo);
//                                builder.body(responseBody);
//
//                                return builder.build();
//                            }
//                            if (original.url().url().getPath().endsWith("api/manager/vote/participants")) {
//                                LogUtil.w(TAG, "【DEMO---------->】表决详情");
//                                // demo-未完成
//                                demo = "{\"code\":0,\"msg\":\"system.success\",\"data\":{\"amount\":29991.0," +
//                                        "\"pageData\":{\"pageNo\":1,\"totalPage\":1,\"pageSize\":10,\"minPage\":1," +
//                                        "\"localArrayList\":[1],\"list\":[{\"creditorName\":\"王庆华\"," +
//                                        "\"bankruptcyProjectId\":\"c316f2035b994ab696889fb084b9d235\"," +
//                                        "\"groupId\":\"48752f4d9c41411a89f4d352d3b4b616\"," +
//                                        "\"voteId\":\"d8b7336332024acbbeae12238695ba97\",\"confirmedMoney\":5017" +
//                                        ".0000000000,\"meetingNumber\":5,\"voteOpinion\":0," +
//                                        "\"id\":\"s3qgoep2ecg98oqacj957hm1b8\"," +
//                                        "\"sysUserId\":\"f9ed9250560a4c49bdbc8bd38fa880e1\",\"voteMoney\":29991" +
//                                        ".0000000000,\"meeting\":false,\"vote\":false," +
//                                        "\"creditorId\":\"b92e9def011043438797de782efd18cc\",\"allowChange\":false}]," +
//                                        "\"totalCount\":4,\"maxPage\":1}}}";
//                                responseBody = ResponseBody.create(MediaType.parse("application/json; charset=utf-8"), demo);
//                                builder.body(responseBody);
//
//                                return builder.build();
//                            }
////
//                            if (original.url().url().getPath().contains("/open/api/creditor/vote/data")) {
//                                LogUtil.w(TAG, "【DEMO---------->】债权人端表决列表");
//                                demo = "{\n" +
//                                        "\"code\": 0,\n" +
//                                        "\"msg\": \"system.success\",\n" +
//                                        "\"data\": {\n" +
//                                        "\"list\": [{\n" +
//                                        "\"id\": \"d8b7336332024acbbeae12238695ba97\",\n" +
//                                        "\"courtHolding\": false,\n" +
//                                        "\"type\": 1,\n" +
//                                        "\"title\": \"api表决重组事项1\",\n" +
//                                        "\"startTime\": 1554076800,\n" +
//                                        "\"endTime\": 1554336000,\n" +
//                                        "\"status\": 2,\n" +
//                                        "\"meeting\": 0,\n" +
//                                        "\"vote\": 0,\n" +
//                                        "\"total\": 1\n" +
//                                        "      }],\n" +
//                                        "\"localArrayList\": [1],\n" +
//                                        "\"totalCount\": 1,\n" +
//                                        "\"pageSize\": 10,\n" +
//                                        "\"pageNo\": 1,\n" +
//                                        "\"minPage\": 1,\n" +
//                                        "\"maxPage\": 1,\n" +
//                                        "\"totalPage\": 1,\n" +
//                                        "\"type\": 1\n" +
//                                        "   }\n" +
//                                        "}\n";
//                                responseBody = ResponseBody.create(MediaType.parse("application/json;charset=utf-8"),
//                                        demo);
//                                builder.body(responseBody);
//
//                                return builder.build();
//                            } else if (original.url().url().getPath().contains("/open/api/creditor/vote/detail")) {
//                                LogUtil.w(TAG, "【DEMO---------->】债权人端表决详情");
//                                demo = "{\n" +
//                                        "    \"code\": 0,\n" +
//                                        "    \"msg\": \"请求成功\",\n" +
//                                        "    \"data\": {\n" +
//                                        "        \"voteInfo\": {\n" +
//                                        "            \"id\": \"d8b7336332024acbbeae12238695ba97\",\n" +
//                                        "            \"bankruptcyProjectId\": \"4r7ffr2b8kg73p7chomb5tp9kl\",\n" +
//                                        "            \"type\": 1,\n" +
//                                        "            \"ruleId\": \"3f6f722420d9409fbe898baf38675985\",\n" +
//                                        "            \"title\": \"api表决重组事项1\",\n" +
//                                        "            \"content\": \"api表决内容1\",\n" +
//                                        "            \"rule\": 1,\n" +
//                                        "            \"ruleName\": \"优先清算规则1\",\n" +
//                                        "            \"ruleExplain\": \"表决规则说明1\",\n" +
//                                        "            \"startTime\": 1554076800,\n" +
//                                        "            \"endTime\": 1554336000,\n" +
//                                        "            \"status\": 2,\n" +
//                                        "            \"files\": [\n" +
//                                        "                {\n" +
//                                        "                    \"id\": \"ossg6k9nu4itrp7k0njgfpm66v\",\n" +
//                                        "                    \"bankruptcyProjectId\": \"4r7ffr2b8kg73p7chomb5tp9kl\"," +
//                                        "\n" +
//                                        "                    \"attachmentName\": \"time.jpg\",\n" +
//                                        "                    \"attachmentSuffix\": \"jpg\",\n" +
//                                        "                    \"attachmentPreviewAddress\": null,\n" +
//                                        "                    \"attachmentDownloadAddress\": \"\",\n" +
//                                        "                    \"attachmentSize\": 20\n" +
//                                        "                },\n" +
//                                        "                {\n" +
//                                        "                    \"id\": \"q8ab59u2sajcoosl8t20p5jsfo\",\n" +
//                                        "                    \"bankruptcyProjectId\": \"4r7ffr2b8kg73p7chomb5tp9kl\"," +
//                                        "\n" +
//                                        "                    \"attachmentName\": \"time.jpg\",\n" +
//                                        "                    \"attachmentSuffix\": \"jpg\",\n" +
//                                        "                    \"attachmentPreviewAddress\": null,\n" +
//                                        "                    \"attachmentDownloadAddress\": \"\",\n" +
//                                        "                    \"attachmentSize\": 20\n" +
//                                        "                }\n" +
//                                        "            ],\n" +
//                                        "            \"groups\": [\n" +
//                                        "                {\n" +
//                                        "                    \"id\": \"48752f4d9c41411a89f4d352d3b4b616\",\n" +
//                                        "                    \"name\": \"债务修改分组名称Q\",\n" +
//                                        "                    \"code\": \"4odfhdtksijh5q3sembtje9a9g\",\n" +
//                                        "                    \"sort\": 1,\n" +
//                                        "                    \"memberCount\": 3\n" +
//                                        "                },\n" +
//                                        "                {\n" +
//                                        "                    \"id\": \"da7da1a8be614c89b8bc542a14eb7d11\",\n" +
//                                        "                    \"name\": \"平台债务分组F\",\n" +
//                                        "                    \"code\": \"uvfkhlf5kmhrrqgc54atej68md\",\n" +
//                                        "                    \"sort\": 2,\n" +
//                                        "                    \"memberCount\": 2\n" +
//                                        "                }\n" +
//                                        "            ]\n" +
//                                        "        },\n" +
//                                        "        \"groupInfo\": [\n" +
//                                        "            {\n" +
//                                        "                \"id\": \"5alkgso69igueribskt0gl2lff\",\n" +
//                                        "                \"meetingNumber\": 1,\n" +
//                                        "                \"creditorId\": \"2\",\n" +
//                                        "                \"meeting\": false,\n" +
//                                        "                \"vote\": false,\n" +
//                                        "                \"voteMoney\": 5365,\n" +
//                                        "                \"name\": \"债务修改分组名称Q\"\n" +
//                                        "            }\n" +
//                                        "        ]\n" +
//                                        "    }\n" +
//                                        "}";
//                                responseBody = ResponseBody.create(MediaType.parse("application/json;charset=utf-8"),
//                                        demo);
//                                builder.body(responseBody);
//
//                                return builder.build();
//                            } else if (original.url().url().getPath().contains("/open/api/creditor/vote/meeting")) {
//                                LogUtil.w(TAG, "【DEMO---------->】债权人端表决--参会");
//                                demo = "{\n" +
//                                        "\"code\": 0,\n" +
//                                        "\"msg\": \"请求成功\",\n" +
//                                        "\"data\": null\n" +
//                                        "}\n";
//                                responseBody = ResponseBody.create(MediaType.parse("application/json;charset=utf-8"),
//                                        demo);
//                                builder.body(responseBody);
//
//                                return builder.build();
//                            } else if (original.url().url().getPath().contains("/open/api/creditor/vote/exitMeeting")) {
//                                LogUtil.w(TAG, "【DEMO---------->】债权人端表决--退出参会");
//                                demo = "{\n" +
//                                        "\"code\": 0,\n" +
//                                        "\"msg\": \"请求成功\",\n" +
//                                        "\"data\": null\n" +
//                                        "}\n";
//                                responseBody = ResponseBody.create(MediaType.parse("application/json;charset=utf-8"),
//                                        demo);
//                                builder.body(responseBody);
//
//                                return builder.build();
//                            } else if (original.url().url().getPath().contains("/open/api/creditor/vote/schedule")) {
//                                LogUtil.w(TAG, "【DEMO---------->】债权人端表决--进度");
//                                demo = "{\n" +
//                                        "    \"code\": 0,\n" +
//                                        "    \"msg\": \"请求成功\",\n" +
//                                        "    \"data\": {\n" +
//                                        "        \"defaultAgreed\": true,\n" +
//                                        "        \"dataList\": [\n" +
//                                        "            {\n" +
//                                        "                \"agreedVoterRate\": 0.33,\n" +
//                                        "                \"disAgreedNum\": 1,\n" +
//                                        "                \"notAttendAmount\": 29991,\n" +
//                                        "                \"groupId\": \"48752f4d9c41411a89f4d352d3b4b616\",\n" +
//                                        "                \"notAtdMoneyRate\": 0.77,\n" +
//                                        "                \"agreedNum\": 1,\n" +
//                                        "                \"notAttendNum\": 1,\n" +
//                                        "                \"agreedMoneyRate\": 0.08,\n" +
//                                        "                \"totalAmount\": 38821,\n" +
//                                        "                \"groupName\": \"债务修改分组名称Q\",\n" +
//                                        "                \"disAgreedMoneyRate\": 0.13,\n" +
//                                        "                \"disAgreedVoterRate\": 0.33,\n" +
//                                        "                \"totalMeetingMember\": 3,\n" +
//                                        "                \"agreedAmount\": 3465,\n" +
//                                        "                \"notAtdVoterRate\": 0.33,\n" +
//                                        "                \"disAgreedAmount\": 5365\n" +
//                                        "            },\n" +
//                                        "            {\n" +
//                                        "                \"agreedVoterRate\": 0.5,\n" +
//                                        "                \"disAgreedNum\": 0,\n" +
//                                        "                \"notAttendAmount\": 5365,\n" +
//                                        "                \"groupId\": \"da7da1a8be614c89b8bc542a14eb7d11\",\n" +
//                                        "                \"notAtdMoneyRate\": 0.19,\n" +
//                                        "                \"agreedNum\": 1,\n" +
//                                        "                \"notAttendNum\": 1,\n" +
//                                        "                \"agreedMoneyRate\": 0.8,\n" +
//                                        "                \"totalAmount\": 27307,\n" +
//                                        "                \"groupName\": \"平台债务分组F\",\n" +
//                                        "                \"disAgreedMoneyRate\": 0,\n" +
//                                        "                \"disAgreedVoterRate\": 0,\n" +
//                                        "                \"totalMeetingMember\": 2,\n" +
//                                        "                \"agreedAmount\": 21942,\n" +
//                                        "                \"notAtdVoterRate\": 0.5,\n" +
//                                        "                \"disAgreedAmount\": 0\n" +
//                                        "            }\n" +
//                                        "        ],\n" +
//                                        "        \"status\": 4\n" +
//                                        "    }\n" +
//                                        "}";
//                                responseBody = ResponseBody.create(MediaType.parse("application/json;charset=utf-8"),
//                                        demo);
//                                builder.body(responseBody);
//
//                                return builder.build();
//                            } else if (original.url().url().getPath().contains("/open/api/creditor/vote/groupList")) {
//                                LogUtil.w(TAG, "【DEMO---------->】债权人端表决--获取债权人表决分组");
//                                demo = "{\n" +
//                                        "    \"code\": 0,\n" +
//                                        "    \"msg\": \"请求成功\",\n" +
//                                        "    \"data\": [\n" +
//                                        "        {\n" +
//                                        "            \"id\": \"5alkgso69igueribskt0gl2lff\",\n" +
//                                        "            \"meetingNumber\": 1,\n" +
//                                        "            \"creditorId\": \"2\",\n" +
//                                        "            \"meeting\": false,\n" +
//                                        "            \"vote\": false,\n" +
//                                        "            \"voteMoney\": 5365,\n" +
//                                        "            \"name\": \"债务修改分组名称Q\"\n" +
//                                        "        }\n" +
//                                        "    ]\n" +
//                                        "}";
//                                responseBody = ResponseBody.create(MediaType.parse("application/json;charset=utf-8"),
//                                        demo);
//                                builder.body(responseBody);
//
//                                return builder.build();
//                            } else if (original.url().url().getPath().contains("/open/api/creditor/vote/vote")) {
//                                LogUtil.w(TAG, "【DEMO---------->】债权人端表决--表决提交");
//                                demo = "{\n" +
//                                        "\"code\": 0,\n" +
//                                        "\"msg\": \"请求成功\",\n" +
//                                        "\"data\": null\n" +
//                                        "}\n";
//                                responseBody = ResponseBody.create(MediaType.parse("application/json;charset=utf-8"),
//                                        demo);
//                                builder.body(responseBody);
//
//                                return builder.build();
//                            } else
//                                if (original.url().url().getPath().contains("/open/api/creditor/vote/participants")) {
//                                LogUtil.w(TAG, "【DEMO---------->】债权人端-表决人员明细");
//                                demo = "{\n" +
//                                        "    \"code\": 0,\n" +
//                                        "    \"msg\": \"system.success\",\n" +
//                                        "    \"data\": {\n" +
//                                        "        \"pageData\": {\n" +
//                                        "            \"list\": [\n" +
//                                        "                {\n" +
//                                        "                    \"id\": \"s3qgoep2ecg98oqacj957hm1b8\",\n" +
//                                        "                    \"bankruptcyProjectId\": \"c316f2035b994ab696889fb084b9d235\",\n" +
//                                        "                    \"voteId\": \"d8b7336332024acbbeae12238695ba97\",\n" +
//                                        "                    \"creditorId\": \"b92e9def011043438797de782efd18cc\",\n" +
//                                        "                    \"confirmedMoney\": 5017,\n" +
//                                        "                    \"voteMoney\": 29991,\n" +
//                                        "                    \"groupId\": \"48752f4d9c41411a89f4d352d3b4b616\",\n" +
//                                        "                    \"meeting\": false,\n" +
//                                        "                    \"meetingTime\": null,\n" +
//                                        "                    \"vote\": false,\n" +
//                                        "                    \"voteTime\": null,\n" +
//                                        "                    \"voteOpinion\": 0,\n" +
//                                        "                    \"supplementOpinion\": null,\n" +
//                                        "                    \"allowChange\": false,\n" +
//                                        "                    \"meetingNumber\": 5,\n" +
//                                        "                    \"creditorName\": \"蛋蛋的忧伤\",\n" +
//                                        "                    \"avatar\": null,\n" +
//                                        "                    \"sysUserId\": \"f9ed9250560a4c49bdbc8bd38fa880e1\"\n" +
//                                        "                },\n" +
//                                        "                {\n" +
//                                        "                    \"id\": \"02243r12qag3prrf93hfjla7iq\",\n" +
//                                        "                    \"bankruptcyProjectId\": \"c316f2035b994ab696889fb084b9d235\",\n" +
//                                        "                    \"voteId\": \"d8b7336332024acbbeae12238695ba97\",\n" +
//                                        "                    \"creditorId\": \"2\",\n" +
//                                        "                    \"confirmedMoney\": 5017,\n" +
//                                        "                    \"voteMoney\": 21942,\n" +
//                                        "                    \"groupId\": \"da7da1a8be614c89b8bc542a14eb7d11\",\n" +
//                                        "                    \"meeting\": true,\n" +
//                                        "                    \"meetingTime\": 1554363760,\n" +
//                                        "                    \"vote\": true,\n" +
//                                        "                    \"voteTime\": 1554364346,\n" +
//                                        "                    \"voteOpinion\": 1,\n" +
//                                        "                    \"supplementOpinion\": \"同意\",\n" +
//                                        "                    \"allowChange\": false,\n" +
//                                        "                    \"meetingNumber\": 3,\n" +
//                                        "                    \"creditorName\": null,\n" +
//                                        "                    \"avatar\": null,\n" +
//                                        "                    \"sysUserId\": null\n" +
//                                        "                },\n" +
//                                        "                {\n" +
//                                        "                    \"id\": \"0uues6p0mei0goqm7d90mpjp1a\",\n" +
//                                        "                    \"bankruptcyProjectId\": \"c316f2035b994ab696889fb084b9d235\",\n" +
//                                        "                    \"voteId\": \"d8b7336332024acbbeae12238695ba97\",\n" +
//                                        "                    \"creditorId\": \"3\",\n" +
//                                        "                    \"confirmedMoney\": 2353,\n" +
//                                        "                    \"voteMoney\": 3465,\n" +
//                                        "                    \"groupId\": \"48752f4d9c41411a89f4d352d3b4b616\",\n" +
//                                        "                    \"meeting\": true,\n" +
//                                        "                    \"meetingTime\": 1554968037,\n" +
//                                        "                    \"vote\": true,\n" +
//                                        "                    \"voteTime\": 1554967406,\n" +
//                                        "                    \"voteOpinion\": 1,\n" +
//                                        "                    \"supplementOpinion\": \"测试1\",\n" +
//                                        "                    \"allowChange\": false,\n" +
//                                        "                    \"meetingNumber\": 2,\n" +
//                                        "                    \"creditorName\": null,\n" +
//                                        "                    \"avatar\": null,\n" +
//                                        "                    \"sysUserId\": null\n" +
//                                        "                },\n" +
//                                        "                {\n" +
//                                        "                    \"id\": \"0uues6p0mei0goqm7d90mpjp1k\",\n" +
//                                        "                    \"bankruptcyProjectId\": \"c316f2035b994ab696889fb084b9d235\",\n" +
//                                        "                    \"voteId\": \"d8b7336332024acbbeae12238695ba97\",\n" +
//                                        "                    \"creditorId\": \"3\",\n" +
//                                        "                    \"confirmedMoney\": 7453,\n" +
//                                        "                    \"voteMoney\": 5365,\n" +
//                                        "                    \"groupId\": \"da7da1a8be614c89b8bc542a14eb7d11\",\n" +
//                                        "                    \"meeting\": false,\n" +
//                                        "                    \"meetingTime\": null,\n" +
//                                        "                    \"vote\": false,\n" +
//                                        "                    \"voteTime\": null,\n" +
//                                        "                    \"voteOpinion\": 0,\n" +
//                                        "                    \"supplementOpinion\": null,\n" +
//                                        "                    \"allowChange\": false,\n" +
//                                        "                    \"meetingNumber\": 1,\n" +
//                                        "                    \"creditorName\": null,\n" +
//                                        "                    \"avatar\": null,\n" +
//                                        "                    \"sysUserId\": null\n" +
//                                        "                },\n" +
//                                        "                {\n" +
//                                        "                    \"id\": \"5alkgso69igueribskt0gl2lff\",\n" +
//                                        "                    \"bankruptcyProjectId\": \"c316f2035b994ab696889fb084b9d235\",\n" +
//                                        "                    \"voteId\": \"d8b7336332024acbbeae12238695ba97\",\n" +
//                                        "                    \"creditorId\": \"2\",\n" +
//                                        "                    \"confirmedMoney\": 7453,\n" +
//                                        "                    \"voteMoney\": 5365,\n" +
//                                        "                    \"groupId\": \"48752f4d9c41411a89f4d352d3b4b616\",\n" +
//                                        "                    \"meeting\": true,\n" +
//                                        "                    \"meetingTime\": 1554363760,\n" +
//                                        "                    \"vote\": true,\n" +
//                                        "                    \"voteTime\": 1554364290,\n" +
//                                        "                    \"voteOpinion\": 0,\n" +
//                                        "                    \"supplementOpinion\": \"同意\",\n" +
//                                        "                    \"allowChange\": false,\n" +
//                                        "                    \"meetingNumber\": 4,\n" +
//                                        "                    \"creditorName\": null,\n" +
//                                        "                    \"avatar\": null,\n" +
//                                        "                    \"sysUserId\": null\n" +
//                                        "                }\n" +
//                                        "            ],\n" +
//                                        "            \"localArrayList\": [\n" +
//                                        "                1\n" +
//                                        "            ],\n" +
//                                        "            \"totalCount\": 5,\n" +
//                                        "            \"pageSize\": 10,\n" +
//                                        "            \"pageNo\": 1,\n" +
//                                        "            \"minPage\": 1,\n" +
//                                        "            \"maxPage\": 1,\n" +
//                                        "            \"totalPage\": 1\n" +
//                                        "        }\n" +
//                                        "    }\n" +
//                                        "}";
//                                responseBody = ResponseBody.create(MediaType.parse("application/json;charset=utf-8"),
//                                        demo);
//                                builder.body(responseBody);
//
//                                return builder.build();
//                            } else if (original.url().url().getPath().contains("/open/api/creditor/vote/group/participants")) {
//                                LogUtil.w(TAG, "【DEMO---------->】债权人端-表决人员明细（分组列表）");
//                                demo = "{\n" +
//                                        "    \"code\": 0,\n" +
//                                        "    \"msg\": \"system.success\",\n" +
//                                        "    \"data\": {\n" +
//                                        "        \"pageData\": {\n" +
//                                        "            \"list\": [\n" +
//                                        "                {\n" +
//                                        "                    \"id\": \"48752f4d9c41411a89f4d352d3b4b616\",\n" +
//                                        "                    \"name\": \"债务修改分组名称Q\",\n" +
//                                        "                    \"code\": \"4odfhdtksijh5q3sembtje9a9g\",\n" +
//                                        "                    \"canDelete\": true,\n" +
//                                        "                    \"ordinary\": true,\n" +
//                                        "                    \"guarantee\": false,\n" +
//                                        "                    \"other\": false,\n" +
//                                        "                    \"voteId\": \"d8b7336332024acbbeae12238695ba97\",\n" +
//                                        "                    \"sort\": 1,\n" +
//                                        "                    \"totalVoteMoney\": 0,\n" +
//                                        "                    \"memberCount\": 2,\n" +
//                                        "                    \"members\": null,\n" +
//                                        "                    \"opBy\": \"\",\n" +
//                                        "                    \"opAt\": 1553738557,\n" +
//                                        "                    \"delFlag\": false\n" +
//                                        "                },\n" +
//                                        "                {\n" +
//                                        "                    \"id\": \"da7da1a8be614c89b8bc542a14eb7d11\",\n" +
//                                        "                    \"name\": \"平台债务分组F\",\n" +
//                                        "                    \"code\": \"uvfkhlf5kmhrrqgc54atej68md\",\n" +
//                                        "                    \"canDelete\": true,\n" +
//                                        "                    \"ordinary\": false,\n" +
//                                        "                    \"guarantee\": true,\n" +
//                                        "                    \"other\": false,\n" +
//                                        "                    \"voteId\": \"d8b7336332024acbbeae12238695ba97\",\n" +
//                                        "                    \"sort\": 2,\n" +
//                                        "                    \"totalVoteMoney\": 0,\n" +
//                                        "                    \"memberCount\": 1,\n" +
//                                        "                    \"members\": null,\n" +
//                                        "                    \"opBy\": \"\",\n" +
//                                        "                    \"opAt\": 1553738557,\n" +
//                                        "                    \"delFlag\": false\n" +
//                                        "                }\n" +
//                                        "            ],\n" +
//                                        "            \"localArrayList\": [\n" +
//                                        "                1\n" +
//                                        "            ],\n" +
//                                        "            \"totalCount\": 2,\n" +
//                                        "            \"pageSize\": 10,\n" +
//                                        "            \"pageNo\": 1,\n" +
//                                        "            \"minPage\": 1,\n" +
//                                        "            \"maxPage\": 1,\n" +
//                                        "            \"totalPage\": 1\n" +
//                                        "        }\n" +
//                                        "    }\n" +
//                                        "}";
//                                responseBody = ResponseBody.create(MediaType.parse("application/json;charset=utf-8"),
//                                        demo);
//                                builder.body(responseBody);
//
//                                return builder.build();
//                            }
                            return response;
                        }
                    })
                    .addInterceptor(new Interceptor() {
                        @Override
                        public Response intercept(final Chain chain) throws IOException {
                            // 原始请求
                            Request request = chain.request();
                            Response response = chain.proceed(request);
                            ResponseBody responseBody = response.body();
                            BufferedSource source = responseBody.source();
                            source.request(Long.MAX_VALUE);
                            String respString = source.buffer().clone().readString(Charset.defaultCharset());
                            // LogUtil.v(TAG, "--->返回报文，respString = " + respString);
                            // TODO 这里判断是否是登录超时的情况
                            JSONObject j = null;
                            try {
                                j = new JSONObject(respString);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            if(j!=null&& (j.optInt("code ") == -10003|| j.optInt("code")==-10004))
                            {
                                LoginNoticeDialog.showPage(j.optString("msg"));
                            }

                            // 这里与后台约定的状态码-10002表示token失效
                            if (j != null && j.optInt("code") == -10002) {
                                Log.w(TAG, "-------->token失效，自动重新获取");
                                HashMap<String, String> params = new HashMap<>();
                                Random random = new Random();
                                String rom = random.nextLong() + "";
                                String timestamp = System.currentTimeMillis() + "";
                                params.put("appid", Consts.APPID);
                                params.put("nonce", rom);
                                params.put("timestamp", timestamp);
                                String sign = SignUtil.createSign(Consts.APPKEY, params);

                                Call<JsonObject> call = getReloginService().getToken(Consts.APPID, rom, timestamp,
                                        sign);
                                JsonObject json = call.execute().body();
                                LogUtil.e(TAG, json.toString());
                                // 自动获取token成功了
                                if (json.get("code").getAsInt() == 0) {
                                    TokenInfo info = TokenInfo.parse(json.get("data").getAsJsonObject());
                                    BankruptcyApp.tokeninfo = info;
                                    SPUtils.getInstance(Consts.SPNAME).put("tokeninfo", info.toString());
                                    Log.w(TAG, "-------->替换最新的token，开始二次请求");
                                    // 最重要的是将当前请求重新执行一遍!!!
                                    Request original = chain.request();
                                    Request.Builder requestBuilder = original.newBuilder();
                                    if (original.body() instanceof FormBody) {
                                        FormBody.Builder newFormBody = new FormBody.Builder();
                                        FormBody oldFormBody = (FormBody) original.body();
                                        for (int i = 0; i < oldFormBody.size(); i++) {
                                            // token替换为最新的
                                            if (TextUtils.equals(oldFormBody.encodedName(i), "token")) {
                                                newFormBody.addEncoded("token", BankruptcyApp.tokeninfo.getToken());
                                            } else {
                                                newFormBody.addEncoded(oldFormBody.encodedName(i),
                                                        oldFormBody.encodedValue(i));
                                            }
                                        }
                                        requestBuilder.method(original.method(), newFormBody.build());
                                    }

                                    response = chain.proceed(requestBuilder.build());
                                    Log.w(TAG, "-------->完成二次请求");
                                } else {
                                    // 自动获取失败，直接返回之前的信息，交由BaseSubscriber处理
                                    Log.w(TAG, "-------->自动获取token失败");
                                }
                            }
                            return response;
                        }
                    })
                    .addInterceptor(loggingInterceptor) // TODO 最后关闭日志
//                    .cookieJar(new CookieJar() {
//                        HashMap<HttpUrl, List<Cookie>> cookieStore = new HashMap<>();
//
//                        @Override
//                        public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
//                            cookieStore.put(url, cookies);
//                        }
//
//                        @Override
//                        public List<Cookie> loadForRequest(HttpUrl url) {
//                            List<Cookie> cookies = cookieStore.get(url);
//                            return cookies != null ? cookies : new ArrayList<Cookie>();
//                        }
//                    })
                    .build();

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(Consts.SERVICEIP)
                    .addConverterFactory(mAfApiConverterFactory)
                    .addCallAdapterFactory(rxJavaCallAdapterFactory)
                    .client(okHttpClient)
                    .build();
            apis = retrofit.create(AFAPIService.class);
        }
        return apis;
    }

    public static ReLoginService getReloginService() {
        if (mReLoginService == null) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

            // OkHttp3.0的使用方式
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(loggingInterceptor)  // TODO 最后关闭日志
                    .build();

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(Consts.SERVICEIP)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(okHttpClient)
                    .build();
            mReLoginService = retrofit.create(ReLoginService.class);
        }
        return mReLoginService;
    }
}